<template>
  <div class="my_uploader">
    <transition name="el-fade-in">
      <draggable v-model="fileList" chosen-class="chosen" force-fallback="true" group="people" animation="1000" class="preview_box" @end="onEnd" v-if="fileList && fileList.length">
        <transition-group name="el-fade-in">
          <div class="preview_img relative" v-for="(file, index) of fileList" :key="'myFileItem' + index">
            <el-image :src="file.fileFullUrl" :preview-src-list="[fileList[index].fileFullUrl]" fit="contain">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
                <p>加载失败</p>
              </div>
            </el-image>

            <div class="absolute star_box" v-if="index == 0">
              <i class="el-icon-star-on"></i>
              <div>封面</div>
            </div>
            <div class="absolute tool_box">
              <div><i class="el-icon-delete pointer" @click="deleteImg(index)" v-if="!disabled"></i></div>
            </div>
          </div>
        </transition-group>
      </draggable>
    </transition>

    <div class="uploader_box relative" v-loading="loading" v-show="(limit && (!fileList.length || (fileList.length && fileList.length < limit))) || (!limit)">
      <div class="text-center">
        <i class="uploader_icon el-icon-upload text-gray absolute"></i>
      </div>
      <input ref="myInputFileRef" type="file" class="my_file_input absolute pointer" :accept="accept" :multiple="multiple" @change="getInputFileChange($event)" v-if="!disabled">
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import { PublicUploadFileItem } from '@/api/PublicServices';
export default {
    name: 'StoreImageComponent',
    components: { draggable },
    props: {
      disabled: {
        type: Boolean,
        default: false
      },
      limit: {
        type: Number,
        default: 5
      },
      accept: {
        type: String,
        default: 'image/*'
      },
      fileSize: {
        type: Number,
        default: 10
      },
      multiple: {
        type: Boolean,
        default: true
      },
      initFiles: {
        type: Array || Object,
        default: null
      },
      path: {
        type: String,
        default: 'middleground/storecenter'
      }
    },
    data() {
      return {
        fileList: [],
        loading: false,
        baseUrl: process.env.VUE_APP_FILE_URL,
        imgFormat: ['jpg','png']
      }
    },
    watch: {
      initFiles: {
        immediate: true,
        handler(newValue) {
          if (!newValue || !newValue.length) return;
          // 过滤，有效的图片地址
          const filerList = newValue.filter(item => item);
          if (filerList && filerList.length) {
            this.fileList = filerList.map(item => {
              if (item.indexOf(this.baseUrl) >= 0) {
                return {
                  fileUrl: item.splice(this.baseUrl + '/')[1],
                  fileBaseUrl: this.baseUrl,
                  fileFullUrl: item
                }
              } else {
                return {
                  fileUrl: item,
                  fileBaseUrl: this.baseUrl,
                  fileFullUrl: this.baseUrl + '/' + item
                }
              }
            })
          } else {
            this.fileList = [];
          }
        }
      }
    },
    methods: {
      onEnd() {
        this.$emit('update', this.fileList);
      },
      // 删除图片
      deleteImg(index) {
        this.fileList.splice(index, 1);
        this.$emit('update', this.fileList);
      },
      getInputFileChange(event) {
        // 限制上传数量
        if (this.limit && this.limit < (this.fileList.length + event.target.files.length)) {
          this.$message.warning('超过上传图片的最大数量限制!');
          return;
        }

        for(let i = 0; i < event.target.files.length; i++) {
          const file = event.target.files[i];
          const fileSize = file.size / 1024 / 1024;
          if (fileSize > this.fileSize) {
            this.$message.warning('图片过大，请重新选择!');
            break;
          }
          const fileName = this.getFileFormat(file.name);
          if (!this.imgFormat.includes(fileName)) {
            this.$message.warning('图片格式错误，请重新选择!');
            return;
          }
          this.privateUploadFunction(file);
        }
        this.$refs.myInputFileRef.value = null;
      },

    // 上传图片api
    privateUploadFunction(file) {
      this.loading = true;
      var formData = new FormData();
      formData.append('file', file, file.name);
      formData.append('useDay', 1);
      formData.append('path', this.path);
      formData.append('projectId', process.env.VUE_APP_FILE_SERVICE_ID);
      PublicUploadFileItem(formData)
      .then(data => {
        this.loading = false;
        if (data.code == 200) {
          this.fileList.push({
            fileUrl: data.data.fileUrl,
            fileBaseUrl: data.data.ip,
            fileFullUrl: data.data.ip + '/' + data.data.fileUrl,
            fileName: data.data.originalFilename
          });
          this.$emit('update', this.fileList);
        } else {
          this.$message.error('图片上传失败!');
        }
      })
      .catch(error => {
        this.loading = false;
        this.$message.error(error);
      })
    },
    getFileFormat(fileString) {
      let filename = fileString;
      let index1 = filename.lastIndexOf('.');
      let index2 = filename.length;
      return filename.substring(index1 + 1, index2).toLowerCase();
    }
  }
}
</script>

<style lang="scss" scoped>
.my_uploader {
  margin: 0 -10px;

  .uploader_box {
    margin: 10px;
    display: inline-block;
    width: 148px;
    height: 148px;
    border-radius: 6px;
    vertical-align: top;
    box-sizing: border-box;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;

    .uploader_icon {
      font-size: 67px;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .my_file_input {
      opacity: 0;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    &:hover {
      border-color: #409eff;
    }
  }

  .preview_box {
    padding: 0;
    display: inline-block;
    // display: flex;
    // justify-content: flex-start;
    // flex-wrap: wrap;
      
    .preview_img {
      margin: 10px;
      width: 148px;
      height: 148px;
      // flex: 0 0 148px;
      border-radius: 4px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      border: 1px dashed #DCDFE6;
      vertical-align: top;

      .star_box {
        width: 42px;
        height: 42px;
        opacity: 0.9;
        background: #ffffff;
        border-top-right-radius: 10px;
        bottom: 0;
        left: 0;
        text-align: center;
        line-height: 1;
        padding-top: 4px;

        i {
          color: orange;
          font-size: 20px;
        }

        > div {
          color: #5A5E66;
          font-size: 12px;
          transform: scale(0.75);
        }
      }

      .tool_box {
        height: 42px;
        opacity: 0.9;
        background: #ffffff;
        bottom: 0;
        right: 0;
        padding: 4px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        border-top-left-radius: 10px;

        > div {
          padding: 4px 8px;

          i {
            color: #5A5E66;
            font-size: 16px;
          }
        }
      }
    }
  }
}
::v-deep .el-image {
    width: 100%;
    height: 100%;
}
</style>
